package com.itheima.gatewaymedia.filters;

import com.itheima.common.constants.SystemConstants;
import com.itheima.common.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关鉴权
 */
@Component
@Slf4j

public class WemediaAuthorizeFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest req = exchange.getRequest();
        ServerHttpResponse resp = exchange.getResponse();
        String path = req.getURI().getPath();
        log.debug("请求地址：{}",path);
        if (path.startsWith("/wemedia/login")){
            return chain.filter(exchange);
        }

        //token校验
        String token = req.getHeaders().getFirst("token");
        if (StringUtils.isNotEmpty(token)){

            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            if (null != claimsBody){
                Integer loginUserId = (Integer) claimsBody.get("id");
                req.mutate().header(SystemConstants.USER_HEADER_NAME,loginUserId.toString());
                return chain.filter(exchange);
            }
            /*int verifyToken = AppJwtUtil.verifyToken(token);
            if (verifyToken == SystemConstants.JWT_OK){
                return chain.filter(exchange);
            }*/
        }

        //没有token
        resp.setStatusCode(HttpStatus.UNAUTHORIZED);
        return resp.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
